#include "operations_data_statistics.h"
#include "ui_operations_data_statistics.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QTextStream>
#include <QStringConverter>
#include <QDateTime>
#include <QDebug>

operations_data_statistics::operations_data_statistics(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::operations_data_statistics)
    , m_isLoading(false)
    , m_retryCount(0)
{
    ui->setupUi(this);
    
    // 获取Api单例实例
    m_api = Api::getInstance();
    
    // 初始化定时器
    m_refreshTimer = new QTimer(this);
    m_refreshTimer->setInterval(REFRESH_INTERVAL);
    
    // 初始化UI
    initializeUI();
    setupConnections();
    
    // 加载数据
    refreshAllData();
    m_refreshTimer->start();
}

operations_data_statistics::~operations_data_statistics()
{
    this->close();

    delete ui;
}

void operations_data_statistics::initializeUI()
{
    // UI设置主要由.ui文件控制，这里只设置动态内容
    
    // 设置默认时间范围
    m_currentTimeRange = tr("本月");
    ui->timeRangeComboBox->setCurrentText(m_currentTimeRange);
    
    // 初始化统计卡片显示
    updateStatisticsCards();
    
    // 初始化状态信息
    updateStatusInfo();
}

void operations_data_statistics::setupConnections()
{
    // 按钮连接
    connect(ui->refreshBtn, &QPushButton::clicked, this, &operations_data_statistics::onRefreshBtnClicked);
    connect(ui->exportBtn, &QPushButton::clicked, this, &operations_data_statistics::onExportBtnClicked);
    
    // 时间范围选择
    connect(ui->timeRangeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &operations_data_statistics::onTimeRangeChanged);
    
    // 自动刷新定时器
    connect(m_refreshTimer, &QTimer::timeout, this, &operations_data_statistics::onAutoRefresh);
    
    // 表格点击事件
    connect(ui->detailsTable, &QTableWidget::cellClicked, this, &operations_data_statistics::onDetailsTableCellClicked);
    connect(ui->detailsTable, &QTableWidget::cellDoubleClicked, this, &operations_data_statistics::onDetailsTableCellDoubleClicked);


}

void operations_data_statistics::loadStatisticsData()
{
    if (m_isLoading) {
        qDebug() << "数据正在加载中，跳过本次请求";
        return;
    }
    
    m_isLoading = true;
    showLoadingState(true);
    
    // 使用API获取统计数据
    QJsonObject apiParams;
    apiParams["timeRange"] = m_currentTimeRange;
    
    auto callback = [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success && response["success"].toBool()) {
            QJsonObject data = response["data"].toObject();
            // 更新统计信息
            updateStatisticsDisplay(data);
            
            // 更新图表
            updateCharts(data);
            
            // 更新表格
            updateTables(data);
            
            showStatusMessage(tr("数据加载成功"), QStringLiteral("success"));
            m_retryCount = 0;
        } else {
            QString errorMsg = response["message"].toString();
            showStatusMessage(tr("数据加载失败: %1").arg(errorMsg), QStringLiteral("error"));
            
            // 重试逻辑
            if (m_retryCount < MAX_RETRY_ATTEMPTS) {
                m_retryCount++;
                QTimer::singleShot(1000 * m_retryCount, this, &operations_data_statistics::loadStatisticsData);
                return;
            }
        }
        
        m_isLoading = false;
        showLoadingState(false);
    };
    
    m_api->get("/api/v1/statistics", apiParams, 10000, callback);
}

void operations_data_statistics::updateStatisticsCards()
{
    // 更新收入卡片
    ui->revenueValue->setText(formatCurrency(m_currentStats.totalRevenue));
    ui->revenueTrend->setText(getTrendIcon(m_currentStats.revenueTrend) + QStringLiteral(" ") + 
                              QString::number(m_currentStats.revenueTrend, 'f', 1) + QStringLiteral("%"));
    // 根据趋势设置样式类
    ui->revenueTrend->setProperty("class", QStringLiteral("statTrend ") + getTrendStyleClass(m_currentStats.revenueTrend));
    ui->revenueTrend->style()->unpolish(ui->revenueTrend);
    ui->revenueTrend->style()->polish(ui->revenueTrend);
    
    // 更新订单卡片
    ui->ordersValue->setText(formatNumber(m_currentStats.totalOrders));
    ui->ordersTrend->setText(getTrendIcon(m_currentStats.ordersTrend) + QStringLiteral(" ") + 
                            QString::number(m_currentStats.ordersTrend, 'f', 1) + QStringLiteral("%"));
    ui->ordersTrend->setProperty("class", QStringLiteral("statTrend ") + getTrendStyleClass(m_currentStats.ordersTrend));
    ui->ordersTrend->style()->unpolish(ui->ordersTrend);
    ui->ordersTrend->style()->polish(ui->ordersTrend);
    
    // 更新用户卡片
    ui->usersValue->setText(formatNumber(m_currentStats.activeUsers));
    ui->usersTrend->setText(getTrendIcon(m_currentStats.usersTrend) + QStringLiteral(" ") + 
                           QString::number(m_currentStats.usersTrend, 'f', 1) + QStringLiteral("%"));
    ui->usersTrend->setProperty("class", QStringLiteral("statTrend ") + getTrendStyleClass(m_currentStats.usersTrend));
    ui->usersTrend->style()->unpolish(ui->usersTrend);
    ui->usersTrend->style()->polish(ui->usersTrend);
    
    // 更新票数卡片
    ui->ticketsValue->setText(formatNumber(m_currentStats.totalTickets));
    ui->ticketsTrend->setText(getTrendIcon(m_currentStats.ticketsTrend) + QStringLiteral(" ") + 
                             QString::number(m_currentStats.ticketsTrend, 'f', 1) + QStringLiteral("%"));
    ui->ticketsTrend->setProperty("class", QStringLiteral("statTrend ") + getTrendStyleClass(m_currentStats.ticketsTrend));
    ui->ticketsTrend->style()->unpolish(ui->ticketsTrend);
    ui->ticketsTrend->style()->polish(ui->ticketsTrend);
}

void operations_data_statistics::updateStatisticsDisplay(const QJsonObject &data)
{
    // 更新总收入
    ui->revenueValue->setText(QString("¥%1").arg(data["totalRevenue"].toString()));
    
    // 更新总订单数
    ui->ordersValue->setText(data["totalOrders"].toString());
    
    // 更新活跃用户数
    ui->usersValue->setText(data["activeUsers"].toString());
    
    // 更新票种数量
    ui->ticketsValue->setText(data["totalTickets"].toString());
}

void operations_data_statistics::updateCharts(const QJsonObject &data)
{
    // 更新收入图表
    QJsonArray revenueData = data["revenueData"].toArray();
    updateRevenueChart(revenueData);
    
    // 更新分类图表
    QJsonArray categoryData = data["categoryData"].toArray();
    updateCategoryChart(categoryData);
}

void operations_data_statistics::updateTables(const QJsonObject &data)
{
    // 更新详细数据表格 - 不传递参数，让updateDetailsTable自己获取数据
    updateDetailsTable();
}

void operations_data_statistics::updateRevenueChart(const QJsonArray &revenueData)
{
    // 由于UI中使用的是占位符标签，这里只更新占位符文本
    QString chartText = "收入趋势图表区域\n";
    
    if (revenueData.isEmpty()) {
        chartText += "暂无数据";
    } else {
        chartText += QString("共 %1 个数据点").arg(revenueData.size());
        
        // 计算总收入
        double totalRevenue = 0;
        for (int i = 0; i < revenueData.size(); ++i) {
            QJsonObject item = revenueData[i].toObject();
            totalRevenue += item["revenue"].toString().remove(QRegularExpression("[^0-9.]")).toDouble();
        }
        chartText += QString("\n总收入: ¥%1").arg(totalRevenue, 0, 'f', 2);
    }
    
    ui->revenueChartPlaceholder->setText(chartText);
}

void operations_data_statistics::updateCategoryChart(const QJsonArray &categoryData)
{
    // 由于UI中使用的是占位符标签，这里只更新占位符文本
    QString chartText = "订单分类饼图区域\n";
    
    if (categoryData.isEmpty()) {
        chartText += "暂无数据";
    } else {
        chartText += QString("共 %1 个分类").arg(categoryData.size());
        
        // 显示各分类信息
        for (int i = 0; i < categoryData.size(); ++i) {
            QJsonObject item = categoryData[i].toObject();
            QString category = item["category"].toString();
            chartText += QString("\n• %1: %2 单").arg(category).arg(item["count"].toString());
        }
    }
    
    ui->categoryChartPlaceholder->setText(chartText);
}

void operations_data_statistics::updateRevenueChart()
{
    // 使用API获取收入图表数据
    m_api->getRevenueChartData(m_currentTimeRange, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success && response["success"].toBool()) {
            QJsonArray revenueData = response["data"].toArray();
            updateRevenueChart(revenueData);
            
            // 更新图表显示
            QString chartText = tr("收入图表已更新 (%1 个数据点)").arg(revenueData.size());
            ui->revenueChartPlaceholder->setText(chartText);
        } else {
            QString chartText = tr("收入图表加载失败: %1").arg(errorMsg);
            ui->revenueChartPlaceholder->setText(chartText);
            showStatusMessage(tr("获取收入图表数据失败: ") + errorMsg, "error");
        }
    });
}

void operations_data_statistics::updateCategoryChart()
{
    // 使用API获取分类图表数据
    m_api->getCategoryChartData(m_currentTimeRange, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success && response["success"].toBool()) {
            QJsonArray categoryData = response["data"].toArray();
            updateCategoryChart(categoryData);
            
            // 更新图表显示
            QString chartText = tr("分类图表已更新 (%1 个分类)").arg(categoryData.size());
            ui->categoryChartPlaceholder->setText(chartText);
        } else {
            QString chartText = tr("分类图表加载失败: %1").arg(errorMsg);
            ui->categoryChartPlaceholder->setText(chartText);
            showStatusMessage(tr("获取分类图表数据失败: ") + errorMsg, "error");
        }
    });
}

QString operations_data_statistics::getPreviousTimeRange(const QString &timeRange)
{
    // 使用API的时间范围计算方法
    return m_api->getPreviousTimeRange(timeRange);
}

double operations_data_statistics::calculateTrend(double current, double previous)
{
    if (previous == 0) {
        return current > 0 ? 100.0 : 0.0;
    }
    
    return ((current - previous) / previous) * 100.0;
}

QString operations_data_statistics::formatCurrency(double amount)
{
    return QStringLiteral("¥%1").arg(QString::number(amount, 'f', 2));
}

QString operations_data_statistics::formatNumber(int number)
{
    return QString::number(number);
}

QString operations_data_statistics::getTrendIcon(double trend)
{
    if (trend > 0) {
        return QStringLiteral("↑");
    } else if (trend < 0) {
        return QStringLiteral("↓");
    } else {
        return QStringLiteral("→");
    }
}

QString operations_data_statistics::getTrendStyle(double trend)
{
    if (trend > 0) {
        return QStringLiteral("color: #4CAF50;");
    } else if (trend < 0) {
        return QStringLiteral("color: #f44336;");
    } else {
        return QStringLiteral("color: #9E9E9E;");
    }
}

QString operations_data_statistics::getTrendStyleClass(double trend)
{
    if (trend > 0) {
        return QStringLiteral("trendUp");
    } else if (trend < 0) {
        return QStringLiteral("trendDown");
    } else {
        return QStringLiteral("trendNeutral");
    }
}

void operations_data_statistics::updateDetailsTable()
{
    ui->detailsTable->setRowCount(0);
    
    // 使用API获取详细数据
    QJsonObject apiParams;
    apiParams["timeRange"] = m_currentTimeRange;
    apiParams["limit"] = 100;
    
    auto callback = [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success && response["success"].toBool()) {
            QJsonArray details = response["details"].toArray();
            
            for (int i = 0; i < details.size(); ++i) {
                QJsonObject detail = details[i].toObject();
                int row = ui->detailsTable->rowCount();
                ui->detailsTable->insertRow(row);
                
                ui->detailsTable->setItem(row, 0, new QTableWidgetItem(detail["date"].toString()));
                ui->detailsTable->setItem(row, 1, new QTableWidgetItem(detail["orders"].toString()));
                ui->detailsTable->setItem(row, 2, new QTableWidgetItem(formatCurrency(detail["revenue"].toString().remove(QRegularExpression("[^0-9.]")).toDouble())));
                ui->detailsTable->setItem(row, 3, new QTableWidgetItem(detail["users"].toString()));
                ui->detailsTable->setItem(row, 4, new QTableWidgetItem(detail["tickets"].toString()));
            }
        } else {
            showStatusMessage(tr("获取详细数据失败: ") + response["message"].toString(), "error");
        }
    };
    
    m_api->get("/api/v1/statistics/details", apiParams, 10000, callback);
}

void operations_data_statistics::updateStatusInfo()
{
    ui->lastUpdateLabel->setText(tr("最后更新: ") + m_currentStats.lastUpdateTime.toString(QStringLiteral("yyyy-MM-dd hh:mm:ss")));
    ui->statusLabel->setText(tr("已连接"));
}

void operations_data_statistics::showLoadingState(bool show)
{
    m_isLoading = show;
    ui->refreshBtn->setEnabled(!show);
    
    if (show) {
        ui->refreshBtn->setText(tr("加载中..."));
    } else {
        ui->refreshBtn->setText(tr("刷新"));
    }
}

void operations_data_statistics::showStatusMessage(const QString &message, const QString &type)
{
    // 简化实现 - 可以在这里添加状态显示逻辑
    qDebug() << "Status:" << type << ":" << message;
}

void operations_data_statistics::handleApiError(const QString &error)
{
    qDebug() << "API Error:" << error;
    showStatusMessage(tr("API错误: ") + error, QStringLiteral("error"));
}

void operations_data_statistics::refreshAllData()
{
    loadStatisticsData();
}

void operations_data_statistics::exportToCSV()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("导出CSV"), 
                                                   QStringLiteral("statistics_%1.csv").arg(QDateTime::currentDateTime().toString(QStringLiteral("yyyyMMdd_hhmmss"))),
                                                   tr("CSV文件 (*.csv)"));
    
    if (fileName.isEmpty()) {
        return;
    }
    
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("错误"), tr("无法创建文件: ") + fileName);
        return;
    }
    
    QTextStream out(&file);
    out.setEncoding(QStringConverter::Utf8);
    
    // 写入表头
    out << tr("日期,订单数,收入,用户数,票数") << "\n";
    
    // 写入数据
    for (int row = 0; row < ui->detailsTable->rowCount(); ++row) {
        QStringList rowData;
        for (int col = 0; col < ui->detailsTable->columnCount(); ++col) {
            QTableWidgetItem *item = ui->detailsTable->item(row, col);
            rowData << (item ? item->text() : QStringLiteral(""));
        }
        out << rowData.join(QStringLiteral(",")) << "\n";
    }
    
    file.close();
    QMessageBox::information(this, tr("成功"), tr("数据已导出到: ") + fileName);
}

// 槽函数实现
void operations_data_statistics::onRefreshBtnClicked()
{
    refreshAllData();
}

void operations_data_statistics::onExportBtnClicked()
{
    exportToCSV();
}

void operations_data_statistics::onTimeRangeChanged(int index)
{
    Q_UNUSED(index)
    m_currentTimeRange = ui->timeRangeComboBox->currentText();
    refreshAllData();
}

void operations_data_statistics::onAutoRefresh()
{
    refreshAllData();
}

void operations_data_statistics::onDetailsTableCellClicked(int row, int column)
{
    Q_UNUSED(row)
    Q_UNUSED(column)
    // 可以在这里添加单元格点击处理逻辑
}

void operations_data_statistics::onDetailsTableCellDoubleClicked(int row, int column)
{
    Q_UNUSED(row)
    Q_UNUSED(column)
    // 可以在这里添加双击处理逻辑
}
